import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { createConversation, getConversationMessages, getUserConversations } from '@/services/conversation'
import type { Conversation, ConversationMessage } from '@/services/conversation'

export const useConversationStore = defineStore('conversation', () => {
  // 状态定义
  const currentConversationId = ref<number | null>(null)
  const conversations = ref<Conversation[]>([])
  const messages = ref<ConversationMessage[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const currentConversation = computed(() => {
    if (!currentConversationId.value) return null
    return conversations.value.find(conv => conv.id === currentConversationId.value) || null
  })

  // Actions

  /**
   * 创建新对话
   * @param title 对话标题
   * @param content 初始消息内容
   * @returns 创建的对话
   */
  async function createNewConversation(title: string, content: string) {
    isLoading.value = true
    error.value = null
    try {
      const conversation = await createConversation(title, content)
      conversations.value.unshift(conversation)
      currentConversationId.value = conversation.id
      return conversation
    } catch (err) {
      error.value = '创建对话失败'
      console.error('创建对话失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 加载用户对话列表
   */
  async function loadConversations() {
    isLoading.value = true
    error.value = null
    try {
      const convs = await getUserConversations()
      conversations.value = convs
    } catch (err) {
      error.value = '加载对话列表失败'
      console.error('加载对话列表失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 加载对话消息
   * @param conversationId 对话ID
   */
  async function loadMessages(conversationId: number) {
    isLoading.value = true
    error.value = null
    try {
      const msgs = await getConversationMessages(conversationId)
      messages.value = msgs
      currentConversationId.value = conversationId
    } catch (err) {
      error.value = '加载对话消息失败'
      console.error('加载对话消息失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 设置当前对话
   * @param conversationId 对话ID
   */
  function setCurrentConversation(conversationId: number | null) {
    currentConversationId.value = conversationId
    if (!conversationId) {
      messages.value = []
    }
  }

  /**
   * 清空当前对话消息
   */
  function clearMessages() {
    messages.value = []
  }

  /**
   * 添加消息到当前对话
   * @param message 消息对象
   */
  function addMessage(message: ConversationMessage) {
    messages.value.push(message)
  }

  /**
   * 更新对话列表
   * @param conv 对话对象
   */
  function updateConversation(conv: Conversation) {
    const index = conversations.value.findIndex(c => c.id === conv.id)
    if (index !== -1) {
      conversations.value[index] = conv
    } else {
      conversations.value.unshift(conv)
    }
  }

  /**
   * 删除对话
   * @param conversationId 对话ID
   */
  function deleteConversation(conversationId: number) {
    conversations.value = conversations.value.filter(conv => conv.id !== conversationId)
    if (currentConversationId.value === conversationId) {
      currentConversationId.value = null
      messages.value = []
    }
  }

  return {
    // 状态
    currentConversationId,
    conversations,
    messages,
    isLoading,
    error,
    // 计算属性
    currentConversation,
    // Actions
    createNewConversation,
    loadConversations,
    loadMessages,
    setCurrentConversation,
    clearMessages,
    addMessage,
    updateConversation,
    deleteConversation
  }
})
